package com.lancoo.androidmultichatroom.demo;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Frank on 2017/7/25.
 */
public class ToolUtil {

    private static String logFilePath = Environment
            .getExternalStorageDirectory() + "/conference2/";

    public static String decodeJson(String str) {
        try {
            return URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encodeJson(String str) {
        try {
            return URLEncoder.encode(str, "utf-8").replace("%2F", "/").replace("%3A", ":").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final boolean ping(String ipaddress) {

        String result = null;
        try {
            // ping 的地址，可以换成任何一种可靠的外网
            String ip = ipaddress;
            // ping网址3次
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 3 " + ip);
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }

    public static boolean ping(String host, int pingCount, StringBuffer stringBuffer) {
        String line = null;
        Process process = null;
        BufferedReader successReader = null;
//        String command = "ping -c " + pingCount + " -w 5 " + host;
        String command = "ping -c " + pingCount + " " + host;
        boolean isSuccess = false;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process == null) {
                append(stringBuffer, "ping fail:process is null.");
                return false;
            }
            successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = successReader.readLine()) != null) {
                append(stringBuffer, line);
            }
            int status = process.waitFor();
            if (status == 0) {
                append(stringBuffer, "exec cmd success:" + command);
                isSuccess = true;
            } else {
                append(stringBuffer, "exec cmd fail.");
                isSuccess = false;
            }
//            LogUtil.i("exec finished.");
            append(stringBuffer, "exec finished.");
        } catch (IOException e) {
//            LogUtil.e(e);
        } catch (InterruptedException e) {
//            LogUtil.e(e);
        } finally {
//            LogUtil.i("ping exit.");
            if (process != null) {
                process.destroy();
            }
            if (successReader != null) {
                try {
                    successReader.close();
                } catch (IOException e) {
//                    LogUtil.e(e);
                }
            }
        }
        return isSuccess;
    }

    private static void append(StringBuffer stringBuffer, String text) {
        if (stringBuffer != null) {
            stringBuffer.append(text + "\n");
        }
    }

    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public static String analysisDomainname(String ip) {
        URL url = null;
        try {
            url = new URL(ip);
            String host = url.getHost();// 获取主机名
            return host;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int analysisDomainPort(String ip) {
        URL url = null;
        try {
            url = new URL(ip);
            // 获取主机名
            int host = url.getPort();
            return host;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getyyyyMMddTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());
        return time;
    }

    public enum Definition {
        //流畅
        lld,
        //标清
        lsd,
        //超清
        lhd
    }



    public static String transEncodeUrl(String url) {
        String translatedPath = "";
        try {
            translatedPath = URLEncoder.encode(url, "utf-8")
                    .replace("%2F", "/").replace("%3A", ":")
                    .replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }// %20为空格
        return translatedPath;
    }


    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }


    public static String getFileName(String httpUrl) {
        if (!TextUtils.isEmpty(httpUrl)) {
            String[] fileSplits = httpUrl.split("/");
            String fileName = fileSplits[fileSplits.length - 1];
            return fileName;
        }
        return "";
    }

    public static void openfile(String path, Context context) {
        Intent intent = new Intent();

        Bundle bundle = new Bundle();
        bundle.putString("OpenMode", "ReadOnly");
        bundle.putBoolean("SendCloseBroad", true);
        bundle.putString("ThirdPackage", "com.lancoo.afterclassondemand");
        bundle.putBoolean("ClearBuffer", true);
        bundle.putBoolean("ClearTrace", true);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setClassName("cn.wps.moffice_eng", "cn.wps.moffice.documentmanager.PreStartActivity2");
        Uri uri = Uri.parse(path);
        intent.setData(uri);
        intent.putExtras(bundle);

        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();

        }
    }
}
